<template>
  <a-drawer
    title="发送模板编辑"
    :visible="visible"
    :destroyOnClose="true"
    width="50%"
    :body-style="{ paddingBottom: '80px' }"
    @close="closeModal"
  >
    <a-form layout="vertical">
      <a-row :gutter="12">
        <a-col :span="24">
          <a-form-item label="配置名称" v-bind="validateInfos.name">
            <a-input
              v-model:value="modelRef.name"
              placeholder="请输入配置名称"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="12">
        <a-col :span="24">
          <h3 style="font-weight: bold">发送通知方式</h3>
        </a-col>
      </a-row>
      <a-form-item>
        <template #label>
          <a-space>
            <span>短信通知</span>
            <a-button
              type="primary"
              ghost
              size="small"
              style="color: #4e50e8; border: 1px solid #4e50e8"
              @click="replaceClick"
              >更换</a-button
            >
          </a-space>
        </template>
        <a-row :gutter="12" style="width: 100%">
          <a-col :span="20">
            <div v-if="!messageInputVisible" style="color: #999">
              {{ modelRef.messageContent }}
              <!-- <EditOutlined
                style="color: #2681f3; cursor: pointer"
                @click="messageInputVisible = true"
              /> -->
            </div>
            <a-textarea
              v-else
              v-model:value="modelRef.messageContent"
              placeholder="请输入短信通知模板内容"
              :rows="3"
              style="width: 733px"
            />
          </a-col>
          <a-col
            :span="4"
            style="
              display: flex;
              justify-content: flex-end;
              align-items: center;
            "
          >
            <a-switch
              checked-children="开"
              v-model:checked="modelRef.message"
            />
          </a-col>
        </a-row>
      </a-form-item>
      <a-divider />

      <a-form-item label="邮件通知">
        <a-row :gutter="12" style="width: 100%">
          <a-col :span="20" style="display: flex; align-items: center">
            <template v-if="!emailInputVisible">
              <div style="color: #999">
                {{ modelRef.emailContent }}
                <EditOutlined
                  style="color: #2681f3; cursor: pointer"
                  @click="emailInputVisible = true"
                />
              </div>
            </template>
            <template v-else>
              <a-textarea
                v-model:value="modelRef.emailContent"
                placeholder="请输入邮件通知模板内容"
                :rows="3"
                style="width: 733px"
                @blur="emailInputVisible = false"
              />
            </template>
          </a-col>
          <a-col
            :span="4"
            style="
              display: flex;
              justify-content: flex-end;
              align-items: center;
            "
          >
            <a-switch
              checked-children="开"
              v-model:checked="modelRef.email"
              @change="onEmailSwitchChange"
            />
          </a-col>
        </a-row>
      </a-form-item>
      <a-divider />

      <a-row :gutter="12" style="width: 100%">
        <a-col
          :span="24"
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <div>
            <span style="color: #333">公众号通知</span>
            <!-- <a-tooltip>
              <template #title>
                未填写正确的公众号自定义模板id时将无法成功发送消息
              </template>
              <QuestionCircleOutlined style="color: #666; margin-left: 5px" />
            </a-tooltip> -->
          </div>
          <a-switch
            checked-children="开"
            v-model:checked="modelRef.weChatPublic"
          />
        </a-col>
      </a-row>
      <a-divider />

      <a-row :gutter="12">
        <a-col :span="24">
          <a-form-item label="选择楼宇" v-bind="validateInfos.relation_builds">
            <a-alert
              v-if="disabledTree"
              show-icon
              type="warning"
              message="该发送模板原来绑定的项目/楼宇，您未全部选中，无法修改。"
              class="mb-10"
            />
            <ChooseHousingResources
              checkType="build"
              :allDisabled="disabledTree"
              :defaultChecked="{ buildList: checkedBuildList }"
              @request="$utils.commonRequest"
              @getResult="getResult"
              @error="setCheckedError"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div class="drawer-footer">
      <a-button class="mr-10" @click.prevent="closeModal">取消</a-button>
      <a-button type="primary" @click.prevent="onSubmit">保存</a-button>
    </div>

    <!-- 更换短信模板 -->
    <ReplaceSMS
      :visible="replaceSMSVisible"
      :text="SMSText"
      @successChange="successChange"
      @cancelChange="replaceSMSVisible = false"
    ></ReplaceSMS>
  </a-drawer>
</template>

<script>
import {
  computed,
  defineComponent,
  nextTick,
  reactive,
  ref,
  toRaw,
  watch,
} from "vue";
import { Form, message } from "ant-design-vue";
import request from "../../../common/utils/request";
import { EditOutlined, QuestionCircleOutlined } from "@ant-design/icons-vue";
import { ChooseHousingResources } from "bl-common-vue3";
import utils from "../../../common/utils/utils";
import ReplaceSMS from "./modules/ReplaceSMS.vue";

const useForm = Form.useForm;

export default defineComponent({
  name: "EditSend",
  components: {
    EditOutlined,
    ChooseHousingResources,
    QuestionCircleOutlined,
    ReplaceSMS,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
  },
  setup(props, context) {
    const id = ref(Number(props.id));

    /**
     * @description: 表单字段
     */
    const modelRef = reactive({
      name: "",
      relation_builds: null,
      message: false,
      email: false,
      messageContent:
        "尊敬的${楼宇名称}租客您好！本期账单最终缴款日期为${应收日期}，请尽快缴纳。请点击${账单链接}查看详情。若已处理请忽略。",
      emailContent:
        "尊敬的${楼宇名称}租客您好！本期账单最终缴款日期为${应收日期}，请尽快缴纳。请点击${账单链接}查看详情。若已处理请忽略。",
      weChatPublic: false,
    });

    /**
     * @description: 验证规则
     */
    const rulesRef = reactive({
      name: [{ required: true, message: "配置名称为必填项" }],
      relation_builds: [{ required: true, message: "请勾选应用楼宇" }],
    });

    /**
     * @description: 触发关闭
     */
    const closeModal = () => {
      context.emit("closeTag");
    };

    /**
     * @description: 创建表单
     */
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const disabledTree = ref(false);
    const checkedBuildList = ref([]);

    const setCheckedError = (e) => {
      disabledTree.value = true;
    };

    const getResult = (info) => {
      if (disabledTree.value) {
        return;
      }
      const { villageList, buildList } = info;
      let list = [];
      if (villageList.length) {
        for (let village of villageList) {
          list = [...list, ...village.children];
        }
      }
      if (buildList.length) {
        list = [...list, ...buildList];
      }
      checkedBuildList.value = list;
    };

    /**
     * @description: 提交表单
     */
    const onSubmit = () => {
      if (!disabledTree.value && checkedBuildList.value.length) {
        modelRef.relation_builds = utils.getProjectBuildByBuildList(
          checkedBuildList.value
        );
      }
      nextTick(() => {
        validate()
          .then(() => {
            let params = { ...toRaw(modelRef) };
            console.log(params);
            let submitParams = {
              name: params.name,
              build_bind: modelRef.relation_builds,
              type_json: [],
              needMsg: true,
            };
            let messageParam = {
              txt: modelRef.messageContent,
              mode: 1,
              status: 1,
            };
            let emailParam = { txt: modelRef.emailContent, mode: 2, status: 1 };
            let publicParam = { mode: 3, status: 1 };
            if (modelRef.message) {
              messageParam.status = 1;
            } else {
              messageParam.status = 0;
            }
            submitParams.type_json.push(messageParam);
            if (modelRef.email) {
              emailParam.status = 1;
            } else {
              emailParam.status = 0;
            }
            submitParams.type_json.push(emailParam);
            if (modelRef.weChatPublic) {
              publicParam.status = 1;
            } else {
              publicParam.status = 0;
            }
            submitParams.type_json.push(publicParam);
            console.log(submitParams);
            context.emit("success", submitParams, props.id);
          })
          .catch((err) => {
            console.log("error", err);
          });
      });
    };

    /**
     * @description: 初始化
     */
    const init = () => {
      if (props.id > 0) {
        getSendDetail();
      }
    };

    const messageInputVisible = ref(false);
    const emailInputVisible = ref(false);

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          // 打开时初始化数据
          init();
        } else {
          // 关闭时重置数据
          resetFields();
          checkedBuildList.value = [];
          disabledTree.value = false;
        }
      }
    );

    let detail = null;
    const getSendDetail = () => {
      request
        .get("/org", "/notice/sendTemplateDetail", {
          id: props.id,
        })
        .then((res) => {
          detail = res.detail;
          modelRef.relation_builds = detail.build_bind;
          if (detail.build_bind.buildId) {
            checkedBuildList.value = detail.build_bind.buildId.map((id) => ({
              id,
            }));
          }
          if (res.detail.name) {
            modelRef.name = res.detail.name;
          }
          if (res.detail.type_json && res.detail.type_json.length > 0) {
            res.detail.type_json.map((jsonItem) => {
              if (jsonItem.mode == 1) {
                modelRef.messageContent = jsonItem.txt;
                if (jsonItem.status == 1) {
                  modelRef.message = true;
                } else {
                  modelRef.message = false;
                }
              }
              if (jsonItem.mode == 2) {
                modelRef.emailContent = jsonItem.txt;
                if (jsonItem.status == 1) {
                  modelRef.email = true;
                } else {
                  modelRef.email = false;
                }
              }
              if (jsonItem.mode == 3) {
                if (jsonItem.status == 1) {
                  modelRef.weChatPublic = true;
                } else {
                  modelRef.weChatPublic = false;
                }
              }
            });
          }
        });
    };

    const onEmailSwitchChange = (checked) => {
      if (!checked) {
        emailInputVisible.value = false;
      }
    };

    // 短信更换按钮
    const replaceSMSVisible = ref(false);
    const SMSText = ref("");
    const replaceClick = () => {
      SMSText.value = "";
      SMSText.value = modelRef.messageContent;
      replaceSMSVisible.value = true;
    };

    const successChange = (text) => {
      replaceSMSVisible.value = false;
      modelRef.messageContent = text;
    };

    return {
      closeModal,
      validateInfos,
      resetFields,
      modelRef,
      onSubmit,
      messageInputVisible,
      emailInputVisible,
      checkedBuildList,
      getResult,
      setCheckedError,
      disabledTree,
      onEmailSwitchChange,
      replaceClick,
      replaceSMSVisible,
      successChange,
      SMSText,
    };
  },
});
</script>

<style>
.labelItem {
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  display: inline-block;
  margin-right: 16px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 20px;
  opacity: 1;
  cursor: pointer;
  position: relative;
}
.labelItem .anticon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
